package com.yeyks.commonReference.append.wxPay.config;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author fuchangshuai
 * @date 2019/4/2 1:33 PM
 */
@Component
public class WeChatYyksBaseConfig {

    @Autowired
    private WeChatYyksBaseProperties wxProperties;

    //获取code对应的openId链接
    private static final String getGzhOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private static final String getXcxOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    public Map<String, String> getWxModel(String type) {
        String appId = null;
        String appSecret = null;
        Map<String, String> map = new HashMap<>();
        /**
         * 小程序
         */
        if ("xcx".equals(type)) {
            appId = wxProperties.getXcxAppId();
            appSecret = wxProperties.getXcxSecret();
        }
        if ("wxpay".equals(type)) {
            appId = wxProperties.getAppAppId();
            appSecret = null;
        }
        if ("gzh".equals(type)) {
            appId = wxProperties.getGzhAppId();
            appSecret = wxProperties.getGzhSecret();
        }
        map.put("appId", appId);
        map.put("appSecret", appSecret);
        if ("xcx".equals(type)) {
            map.put("url", getXcxOpenIdUrl);
        }
        if ("gzh".equals(type)) {
            map.put("url", getGzhOpenIdUrl);
        }
        return map;
    }

    /**
     * 微信授权service
     *
     * @return
     */
    @Bean
    public WxMpService initWxMpService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(wxProperties.getGzhAppId());
        config.setSecret(wxProperties.getGzhSecret());
        wxMpService.setWxMpConfigStorage(config);
        return wxMpService;
    }

    /**
     * 获取code获取openId的链接
     *
     * @param type
     * @param code
     * @return
     */
    public String getOpenIdUrl(String type, String code) {
        Map<String, String> map = getWxModel(type);
        return String.format(map.get("url"), map.get("appId"), map.get("appSecret"), code);
    }

}
